package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.utils.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


/**
 * crm 授权
 */
@Service
public class AccessTokenImpl {
    private final static Logger log = LoggerFactory.getLogger(AccessTokenImpl.class);

    private final static String WechatAppId="wx396e3ba737824789";
    private final static String WechatAppSercet="b24e63260a5a33e8fcb411da1e2e60ea";

    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private RedisUtils redisUtils;

    private static final long ONE_DAY = 60 * 90L;

    public String getAccessToken() {
        //查询数据库 accessToken 是否存在 ，不存在查询crm
        String detailKey = "CRMAccessToken";
        if (!redisUtils.exists(detailKey)) {
            String requestUrl = Constants.GetCRMAccessTokenUrl.replace("CRMAPPID", Constants.CRMAPPID).replace("CRMSECRET", Constants.CRMSECRET);
            log.info(" start request URL = {} ", requestUrl);
            JSONObject result = restTemplate.getForEntity(requestUrl, JSONObject.class).getBody();
            String accessToken = result.getString("access_token");
            redisUtils.set(detailKey, accessToken, ONE_DAY);
            log.info("CRMAccessToken={}",String.valueOf(redisUtils.get(detailKey)));
            return accessToken;
        }
        String accessToken = String.valueOf(redisUtils.get(detailKey));
        log.info("CRMAccessToken={}",String.valueOf(redisUtils.get(detailKey)));
        return accessToken;
    }

    public String getWechatAccessToken() {
        //查询数据库 accessToken 是否存在 ，不存在查询crm
        String detailKey = "WechatAccessToken";
        if (!redisUtils.exists(detailKey)) {
            String requestUrl = Constants.GetAccessTokenUrl.replace("APPID", WechatAppId).replace("APPSECRET", WechatAppSercet);
            log.info(" start request URL = {} ", requestUrl);
            JSONObject result = restTemplate.getForEntity(requestUrl, JSONObject.class).getBody();
            String accessToken = result.getString("access_token");
            redisUtils.set(detailKey, accessToken, ONE_DAY);
            log.info("WechatAccessToken={}",String.valueOf(redisUtils.get(detailKey)));
            return accessToken;
        }
        String accessToken = String.valueOf(redisUtils.get(detailKey));
        log.info("WechatAccessToken={}",String.valueOf(redisUtils.get(detailKey)));
        return accessToken;
    }
}
